package br.com.fiap.mercadinho.servlet;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.fiap.mercadinho.bean.Customer;
import br.com.fiap.mercadinho.bean.Order;
import br.com.fiap.mercadinho.bean.Stock;
import br.com.fiap.mercadinho.common.DAOException;
import br.com.fiap.mercadinho.common.RequestKey;
import br.com.fiap.mercadinho.dao.CustomerDAO;
import br.com.fiap.mercadinho.dao.OrderDAO;
import br.com.fiap.mercadinho.dao.StockDAO;

/**
 * Servlet implementation class OrderServlet
 */
@WebServlet("/order")
public class OrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OrderServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		

		OrderDAO dao = new OrderDAO();
		CustomerDAO customerDAO = new CustomerDAO();
		String resultPage = "viewOrder.jsp";
		String customerId = request.getParameter("customerId");
		List<Customer> listCustomers;
		try {
			listCustomers = customerDAO.findAllCustomer();
			List<Order> orders;
			if (customerId != null){
				Customer customer = customerDAO.findCustomerById(Integer.valueOf(customerId));
				orders = dao.findOrderByCustomerId(Integer.parseInt(customerId));
				request.setAttribute("customer",customer);
			}else{
				orders = dao.findOrderByCustomerId(listCustomers.get(0).getId());
				request.setAttribute("customer",listCustomers.get(0));
			}
			request.setAttribute("orderList", orders);
			request.setAttribute("customerList", listCustomers);
			resultPage = "viewOrder.jsp";
		} catch (DAOException e) {
			request.setAttribute(RequestKey.INFO_MESSAGE_KEY.getValue(),
					e.getMessage());
			sendResponse(request, response,"viewOrder.jsp");
		}
		sendResponse(request, response, resultPage);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		OrderDAO dao = new OrderDAO();
		CustomerDAO customerDAO = new CustomerDAO();
		StockDAO stockDAO = new StockDAO();
		String resultPage = "viewOrder.jsp";
		try {
			String action = request.getParameter("action");
			request.setAttribute("action", action);
			String customerId = request.getParameter("customerId");


			if (action.equals("show")) {
				List<Customer> listCustomers = customerDAO.findAllCustomer();
				List<Order> orders = dao.findOrderByCustomerId(listCustomers.get(0).getId());
				request.setAttribute("orderList", orders);
				request.setAttribute("customer", listCustomers.get(0));
				request.setAttribute("customerList", listCustomers);
				resultPage = "viewOrder.jsp";
				
			}else if (action.equals("findOrder")){
				List<Customer> listCustomers = customerDAO.findAllCustomer();
				List<Order> orders = dao.findOrderByCustomerId(Integer.valueOf(customerId));
				request.setAttribute("orderList", orders);
				request.setAttribute("customer", customerDAO.findCustomerById(Integer.valueOf(customerId)));
				request.setAttribute("customerList", listCustomers);
				resultPage = "viewOrder.jsp";
			}else if (action.equals("create")) {
				Customer customer = customerDAO.findCustomerById(Integer.valueOf(customerId));
				request.setAttribute("customer", customer);
			
				//create order in session
				Order order = new Order();
				order.setCustomer(customer);
				request.getSession().setAttribute("order", order);
				
				//recovery and store in session list of stock products for refresh the quantitys
				Map<Integer, Stock> products = stockDAO.getStockProductsMap();
				request.getSession().setAttribute("productList", products);
				
				//set the first product of list for complete screen fields.
				Iterator<Stock> product = products.values().iterator();
				
				Stock prd = product.next();
				
				request.setAttribute("product",prd);
				
				request.setAttribute("productQuantitySelected", 0);
				resultPage = "order.jsp";
			}else if (action.equals("findProduct")){
				Integer stockProductId = Integer.valueOf(request.getParameter("productIdSelected"));
				Map<Integer, Stock> stockMap = (Map<Integer, Stock>)request.getSession().getAttribute("productList");
				
				request.setAttribute("product", stockMap.get(stockProductId));
				request.setAttribute("productQuantitySelected", 0);
				Customer customer = customerDAO.findCustomerById(Integer.valueOf(customerId));
				request.setAttribute("customer", customer);
				resultPage = "order.jsp";
			}else if (action.equals("add")) {
			
				//recovery order and stock products from session
				Order order = (Order)request.getSession().getAttribute("order");
				Map<Integer, Stock> stockMap = (Map<Integer, Stock>)request.getSession().getAttribute("productList");
				
				//recover product and quantity selected by user and verify the avaible in stock
				Integer stockProductId = Integer.valueOf(request.getParameter("productIdSelected"));
				Integer quantity = Integer.valueOf(request.getParameter("productQuantitySelected"));
				Stock productStock = stockMap.get(stockProductId);
				
				
				//verify quantity of product
				if (quantity > productStock.getQuantity()){
					request.setAttribute(RequestKey.INFO_MESSAGE_KEY.getValue(),
							"A quantidade do produto solicitada nao existe no estoque.");
				}else if (quantity <= 0){
					request.setAttribute(RequestKey.INFO_MESSAGE_KEY.getValue(),
							"A quantidade do produto solicitada deve ser maior que zero.");
				}else {
					//add item in order
					order.addProduct(productStock.getProduct(),quantity);
					//store order in session
					request.getSession().setAttribute("order", order);
					productStock.subtractQuantityProduct(quantity);
					
				}
				
				request.setAttribute("product", stockMap.get(stockProductId));
				request.setAttribute("productQuantitySelected", 0);
				
				//refresh customer data
				Customer customer = customerDAO.findCustomerById(Integer.valueOf(customerId));
				request.setAttribute("customer", customer);
				
				resultPage = "order.jsp";
			} else if (action.equals("removeItem")) {
			
				//recovery order from session
				Order order = (Order)request.getSession().getAttribute("order");
				Map<Integer, Stock> stockMap = (Map<Integer, Stock>)request.getSession().getAttribute("productList");
				
				//recover product  selected by user for remove from list
				Integer stockProductId = Integer.valueOf(request.getParameter("productIdSelected"));
				Stock productStock = stockMap.get(stockProductId);
			
				
				//remove item from order
				productStock.addQuantityProduct(productStock.getProduct().getQuantity());
				order.removeProduct(productStock.getProduct());
			
				//store the order.
				request.getSession().setAttribute("order", order);
				
				request.setAttribute("product", stockMap.get(stockProductId));
				request.setAttribute("productQuantitySelected", 0);
				
				//refresh customer data
				Customer customer = customerDAO.findCustomerById(Integer.valueOf(customerId));
				request.setAttribute("customer", customer);
	
				resultPage = "order.jsp";
			}else if (action.equals("saveOrder")){
				//recovery order from session
				Order order = (Order)request.getSession().getAttribute("order");
				
				if (!order.getProducts().isEmpty()){
				
				//save the order in data base
				order.saveOrderWithProducts();
				//redirect user to orderview;
				response.sendRedirect("order?action=show&customerId=" + order.getCustomer().getId());
				return ;
				}else{
					request.setAttribute(RequestKey.INFO_MESSAGE_KEY.getValue(),
							"Voce precisa ter ao menos um item no pedido de compra para finaliza-lo.");
					resultPage = "order.jsp";
				}
				
			}else if (action.equals("select")){
				Customer customer = customerDAO.findCustomerById(Integer.valueOf(customerId));
				request.setAttribute("customer", customer);
			
				String orderId = request.getParameter("orderIdSelected");
				Order order = dao.findOrderById(Integer.valueOf(orderId));
				request.getSession().setAttribute("order", order);
				
				
				//recovery and store in session list of stock products for refresh the quantitys
				Map<Integer, Stock> products = stockDAO.getStockProductsMap();
				request.getSession().setAttribute("productList", products);
				
				//set the first product of list for complete screen fields.
				Iterator<Stock> product = products.values().iterator();
				
				Stock prd = product.next();
				
				request.setAttribute("product",prd);
				
				request.setAttribute("productQuantitySelected", 0);
				
				resultPage = "order.jsp";
			}
			sendResponse(request, response,resultPage);
		} catch (DAOException e) {
			request.setAttribute(RequestKey.INFO_MESSAGE_KEY.getValue(),
					e.getMessage());
			sendResponse(request, response,"viewOrder.jsp");
		}

	}

	private void sendResponse(HttpServletRequest request,
			HttpServletResponse response,String page) throws ServletException, IOException {
		request.getRequestDispatcher(page).forward(request, response);
	}




}
